<template>
    <div>
      动态组件2 简单购物车
      <div v-if="books.length!=0">
        <table >
          <thead>
          <tr>
            <th></th>
            <th>书籍名字</th>
            <th>出版日期</th>
            <th>单价</th>
            <th>购买数量</th>
            <th>总价</th>
            <th>删除</th>
            <th>添加</th>
          </tr>
          </thead>

          <tbody>
          <tr v-for="(book,index) in books">
            <td>{{book.id}}</td>
            <td>{{book.name}}</td>
            <td>{{book.date}}</td>
            <td>{{book.price | showPrice }}</td>
            <td><button @click="add(index)">+</button>{{book.count}}<button @click="dec(index)" :disabled="book.count<=1">-</button></td>
            <td>{{book.price * book.count| showPrice }}</td>
            <td><button @dblclick="remove(index)">双击移除</button></td>
            <td><button @click = "addIndex">添加</button></td>
          </tr>
          </tbody>

          <tfoot>
          <tr>
            <td colspan="7">合计:{{totalPrice | showPrice }}</td>
            <!-- 不是form表单提不上去-->
            <td><button type="submit">提交</button></td>
          </tr>
          </tfoot>
        </table>
      </div>
      <h2 v-else> 购物车为空</h2>
    </div>
</template>

<script>
    export default {
        name: "Example1",
        data(){
            return{
              books:[
                {id:1,name:"java1",date:2006-9,price:100,count:1},
                {id:2,name:"java2",date:2006-10,price:200,count:1},
                {id:3,name:"java3",date:2006-11,price:300,count:1}
              ]
            }
        },
      computed:{
        totalPrice(){
          let total = this.books.reduce(function (prev,cur) {
            return prev+=cur.price*cur.count;
          },0);
          return total
        }
      },

        methods:{
          add(index){
            this.books[index].count++
          },
          dec(index){
            this.books[index].count--
          },
          remove(index){
            this.books.splice(index,1)
          },
          addIndex(index){
            this.books.splice(this.books.length,0,{
              id:this.books.length+1,
              name:"java3",
              date:2006-11,
              price:300,
              count:1
            })
          }
        },
      //过滤器
      filters:{
        showPrice(price){
          return '￥' + price.toFixed(2)
        }
      }
    }
</script>

<style scoped>
  table{
    /*width:50%;*/
    border:  1px solid #e9e9e9;
    border-collapse: collapse;
    border-spacing: 0;
  }
  th,td{
    /*表格的大小,在不设置width的情况下,可以使用padding扩大*/
    padding: 8px 16px;
    border: 1px solid #e9e9e9 ;
    text-align: left;
  }
  th{
    background-color: #f7f7f7;
    color: #5c6b77;
    font-weight: bold;
  }
</style>
